// pages/post1/post1.js
const app = getApp(), core = require('../../utils/core'), WeValidator = require('../../utils/we-validator');
WeValidator.addRule('salary',{
  message: '薪资至少填写一项',
  rule(value, param) {
    if(value!==0) {//薪资不为面议
      return !(!this.data.salary_max && !this.data.salary_min);
    }
    return true;
  }
});
Page({

  /**
   * 页面的初始数据
   */
  data: {
    job: {},
    // salaryTypes: ['按小时结算', '按天结算', '按月结算'],
    salaryTypes: [{id:3,name:'按月结算'},{id:2,name:'按天结算'},{id:1,name:'按小时结算'}],
    salaryPickerIndex: 0,
    unit: '',
  },
  onLoad: function (options) {
    this.getOpenerEventChannel().on('jobTransfer', job => {
      this.setData({job: job});
      this._formatUnit();
      let salaryPickerIndex = 0;
      for(let i=0;i<this.data.salaryTypes.length;i++) {
        let item = this.data.salaryTypes[i];
        if(item.id==job.salary_type) {
          salaryPickerIndex = i;
          break;
        }
      }
      this.setData({salaryPickerIndex});
    });
  },
  _formatUnit() {
    let type = this.data.job.salary_type;
    if(type===1) {
      this.setData({
        'unit': '元/时'
      })
    }else if(type===2) {
      this.setData({
        'unit': '元/日'
      })
    }else if(type===3) {
      this.setData({
        'unit': '元/月'
      })
    }
  },
  bindSalaryPick: function (e) {
    let index = parseInt(e.detail.value), type = this.data.salaryTypes[index].id;
    this.setData({
      salaryPickerIndex: index,
      'job.salary_type': type,
    });
    this._formatUnit();
  },
  bindSalaryTypeChange: function (e) {
    let type = e.currentTarget.dataset.type;
    this.setData({
      'job.salary_type': type
    });
    if(type===0) {
      this.setData({
        'job.salary_max': null,
        'job.salary_min': null,
        'unit': '',
      });
    }else {
      this.setData({
        'unit': ''
      })
    }
  },
  bindSalaryMinInput: function (event) {
    this.setData({'job.salary_min':event.detail.value});
  },
  bindSalaryMaxInput: function (event) {
    this.setData({'job.salary_max':event.detail.value});
  },
  bindNextStep: function () {

    let validator = new WeValidator({
      rules: {
        salary_type: {required:true, range:[0,3], salary:true},
        salary_min: {digits:true},
        salary_max: {digits:true},
      },
      messages: {
        salary_type: {required:'请选择结薪方式', range:'请选择结薪方式', salary:'薪资至少填写一项'},
        salary_min: {digits:'薪资请填写正整数'},
        salary_max: {digits:'薪资请填写正整数'},
      }
    });
    if(!validator.checkData(this.data.job)) {
      return;
    }
    wx.navigateTo({url: '/pages/post2/post2', success: res => {
      res.eventChannel.emit("jobTransfer", this.data.job);
    }});
  },
});
